import { Vector2 } from 'three';
import AbstractHandler, { HandlerEvent } from './AbstractHandler';

type EventMap = HandlerEvent<'pitchEnd'> | HandlerEvent<'rotateEnd'>;

class DragRotate extends AbstractHandler<EventMap> {
  private _lastPoint?: Vector2;

  mousedown(e: MouseEvent) {
    if (e.buttons !== 2 || this._state === 'disable') return;
    this._lastPoint = new Vector2(e.clientX, e.clientY);
  }

  mousemove(e: MouseEvent) {
    if (!this._lastPoint || e.buttons !== 2) return;
    const current = new Vector2(e.clientX, e.clientY);
    const engine = this._handlerManager.getView().getEngine();
    const camera = engine.getCamera();
    const delta = current.clone().sub(this._lastPoint);
    let bearing = camera.getBearing();
    bearing += delta.x / 3;
    let pitch = camera.getPitch();
    pitch -= delta.y / 3;
    camera.set({ bearing, pitch });
    engine.render();
    this._lastPoint = current;
  }

  mouseup(e: MouseEvent) {
    if (e.buttons !== 2) return;
    this._end();
  }

  mouseleave(e: MouseEvent) {
    if (e.buttons !== 2) return;
    this._end();
  }

  private _end() {
    delete this._lastPoint;
  }
}

export default DragRotate;
